﻿using System;
using System.Collections.Generic;
using NPOI.XWPF.UserModel;
using System.IO;
using System.Diagnostics;

namespace FillWordDataByTemplate
{
    internal class Class2
    {

        /// <summary>
        /// 存放word中需要替换的关键字以及对应要更改的内容
        /// </summary>
        public Dictionary<string, string> DicWord = new Dictionary<string, string>();

        /// <summary>
        /// Word模板路径
        /// </summary>
        private string path = @"E:\Users\Documents\Visual Studio 2013\Projects\用NPOI读写Word\FillWordDataByTemplate\_files_\这是模板3.docx";

        /// <summary>
        /// 更改后的文件路径
        /// P.S. 当然可以直接修改模板文件，这里另外生成文件是个人为了方便测试。
        /// </summary>
        //private string targetPath = "C:\\Users\\USER\\Desktop\\文本测试\\目标文件夹\\马摆摊.docx";
        string targetPath =
                @"E:\Users\Documents\Visual Studio 2013\Projects\用NPOI读写Word\FillWordDataByTemplate\_files_\这是新文件" +
                DateTime.Now.ToString("yyyyMMdd_HHmmss") +
                ".docx";

        private void Start()
        {
            DicWord.Add("$电话$", "要生死生生爸爸要武要爸");
            DicWord.Add("$罚款$", "普希金");
            DicWord.Add("$content$",
                "假如生活欺骗了你假如生活欺骗了你，不要悲伤，不要心急！忧郁的日子里须要镇静：相信吧，快乐的日子将会来临！心儿永远向往着未来；现在却常是忧郁。一切都是瞬息，一切都将会过去；而那过去了的，就会成为亲切的怀恋。");
            DicWord.Add("$交钱$", "黄药师");
            DicWord.Add("$西毒$", "欧阳锋");
            DicWord.Add("$南帝$", "一灯");
            DicWord.Add("$北丐$", "洪七公");

            ReplaceKeyword();
        }

        /// <summary>
        /// 替换关键字
        /// </summary>
        private void ReplaceKeyword()
        {
            using (FileStream stream = File.OpenRead(path))
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                XWPFDocument doc = new XWPFDocument(fs);

                //遍历段落                  
                foreach (var para in doc.Paragraphs)
                {
                    string oldText = para.ParagraphText;
                    if (oldText != "" && oldText != string.Empty && oldText != null)
                    {
                        string tempText = para.ParagraphText;
                        foreach (KeyValuePair<string, string> kvp in DicWord)
                        {
                            if (tempText.Contains(kvp.Key))
                            {
                                tempText = tempText.Replace(kvp.Key, kvp.Value);
                                para.ReplaceText(oldText, tempText);
                            }
                        }

                    }
                }

                //遍历表格      
                var tables = doc.Tables;
                foreach (var table in tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                string oldText = para.ParagraphText;
                                if (oldText != "" && oldText != string.Empty && oldText != null)
                                {
                                    //记录段落文本
                                    string tempText = para.ParagraphText;
                                    foreach (KeyValuePair<string, string> kvp in DicWord)
                                    {
                                        if (tempText.Contains(kvp.Key))
                                        {
                                            tempText = tempText.Replace(kvp.Key, kvp.Value);

                                            //替换内容
                                            para.ReplaceText(oldText, tempText);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //生成指定文件
                FileStream output = new FileStream(targetPath, FileMode.Create);
                //将文档信息写入文件
                doc.Write(output);

                //一些列关闭释放操作
                fs.Close();
                fs.Dispose();
                output.Close();
                output.Dispose();

                //Process.Start(targetPath); //打开指定文件
            }
        }
    }
}
